<script setup lang="ts">
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import {ElMessage} from "element-plus";
import type {FormInstance} from 'element-plus'
import {ProductForm, ProductBomDto} from '@/api/product/type'
import {addApi, editApi, getBomDetailByIdApi} from '@/api/product'
import {Plus} from '@element-plus/icons-vue'
import BomDialog from '@/views/compute/bom/bomDialog/index.vue'

// 定义组件属性
const props = defineProps<{
  productId?: number // 产品ID，编辑时传入
  mode: string // 组件模式：add/edit/view
}>()

// 定义组件事件
const emit = defineEmits(['save-success', 'cancel'])

// 表单ref，用于表单验证
const formRef = ref<FormInstance>()

// BOM选择弹框组件实例
const bomDialogRef = ref()

// 初始化表单数据
const formData = reactive<ProductForm>({
  id: undefined,
  productCode: undefined,
  productName: undefined,
  description: undefined,
  productBomDtoList: [] as ProductBomDto[],
})

// 已选BOM
const selectedBoms = ref<any[]>([])

// 表单校验规则
const rules = {
  productCode: [{required: true, message: '请输入产品编码', trigger: 'blur'}],
  productName: [{required: true, message: '请输入产品名称', trigger: 'blur'}],
}

// 打开BOM选择弹窗
const openBomSelect = () => {
  bomDialogRef.value.onShow()
}

// BOM多选变化事件处理
const handleBomSelectionChange = (selection: any[]) => {
  selectedBoms.value = selection
}

// 确认BOM选择
const confirmBomSelect = () => {
  selectedBoms.value.forEach((bom) => {
    const exists = formData.productBomDtoList.some(
        (item) => item.bomId === bom.id
    )
    if (!exists) {
      formData.productBomDtoList.push({
        id: undefined,
        productId: formData.id,
        bomId: bom.id,
        bomCode: bom.bomCode,
        bomName: bom.bomName,
        quantity: 1, // 默认数量为1
        materialTotalPrices: bom.materialTotalPrices,
        processTotalPrices: bom.processTotalPrices,
        totalPrices: bom.totalPrices, // BOM单价
        cost: bom.totalPrices, // 初始cost等于单价（因为数量为1）
        description: '',
      })
    }
  })
  bomDialogRef.value.onClose()
}

// 从BOM清单中移除BOM
const removeBom = (index: number) => {
  formData.productBomDtoList.splice(index, 1)
}

// 计算单个BOM的成本
const calculateBomCost = (row: ProductBomDto) => {
  if (row.quantity && row.totalPrices) {
    // totalPrices是单价，cost是总价
    row.cost = Number((row.quantity * row.totalPrices).toFixed(2))
  }
}

// 处理提交数据
const handleSubmitData = () => {
  const submitData = JSON.parse(JSON.stringify(formData))

  // 处理BOM清单数据
  submitData.productBomDtoList = submitData.productBomDtoList.map(
      (item: ProductBomDto) => ({
        id: item.id,
        productId: submitData.id,
        bomId: item.bomId,
        quantity: Number(item.quantity),
        cost: Number(item.cost), // 添加cost字段
        description: item.description || '',
      })
  )

  return submitData
}

// 提交表单
const submitForm = async () => {
  if (props.mode === 'view') return

  try {
    await formRef.value?.validate()
    if (formData.productBomDtoList.length === 0) {
      ElMessage.warning('请选择BOM')
      return
    }

    const submitData = handleSubmitData()
    if (props.mode === 'add') {
      await addApi(submitData)
    }
    if (props.mode === 'edit') {
      await editApi(submitData)
    }

    ElMessage.success('保存成功')
    emit('save-success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('保存失败')
  }
}

// 取消操作
const cancel = () => {
  emit('cancel')
}

// 监听productId变化,当编���时加载产品详情
watch(
    () => props.productId,
    async (newVal) => {
      if (newVal) {
        try {
          const res = await getBomDetailByIdApi(newVal)
          if (res?.data) {
            // 重置表单数据
            formData.id = res.data.id
            formData.productCode = res.data.productCode
            formData.productName = res.data.productName
            formData.description = res.data.description

            // 处理BOM清单数据
            formData.productBomDtoList = res.data.productBomVoList.map((item: any) => ({
              id: item.id,
              productId: item.productId,
              bomId: item.bomId,
              bomCode: item.bomCode,
              bomName: item.bomName,
              quantity: item.quantity,
              materialTotalPrices: item.materialTotalPrices,
              processTotalPrices: item.processTotalPrices,
              totalPrices: item.totalPrices,
              cost: item.quantity * item.totalPrices, // 计算初始cost
              description: item.description || ''
            }))
          }
        } catch (error) {
          console.error('获取产品详情失败:', error)
          ElMessage.error('获取产品详情失败')
        }
      } else {
        // 新增时重置表单
        formData.id = undefined
        formData.productCode = undefined
        formData.productName = undefined
        formData.description = undefined
        formData.productBomDtoList = []
      }
    },
    {immediate: true}
)
</script>

<template>
  <div class="product-form">
    <div class="form-header">
      <h3>{{ mode === 'add' ? '新增产品' : mode === 'edit' ? '编辑产品' : '产品详情' }}</h3>
    </div>

    <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="90px"
        :disabled="mode === 'view'"
    >
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="formData.productCode" placeholder="请输入产品编码"/>
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="formData.productName" placeholder="请输入产品名称"/>
      </el-form-item>

      <!-- BOM清单 -->
      <el-form-item label="BOM清单" prop="productBomDtoList">
        <el-button
            type="primary"
            @click="openBomSelect"
            style="margin-bottom: 10px"
            :icon="Plus"
        >
          添加BOM
        </el-button>
        <el-table :data="formData.productBomDtoList" border style="width: 100%">
          <el-table-column type="index" label="序号" width="70"/>
          <el-table-column prop="bomCode" label="BOM编码" min-width="120"/>
          <el-table-column prop="bomName" label="BOM名称" min-width="120"/>
          <el-table-column prop="quantity" label="数量" width="120">
            <template #default="scope">
              <el-input-number
                  v-model="scope.row.quantity"
                  :min="1"
                  :precision="0"
                  style="width: 100px"
                  @change="calculateBomCost(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="totalPrices" label="单价" min-width="120"/>
          <el-table-column prop="cost" label="总价" min-width="120"/>
          <el-table-column prop="materialTotalPrices" label="物料总价" min-width="120"/>
          <el-table-column prop="processTotalPrices" label="工序总价" min-width="120"/>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button
                  type="danger"
                  link
                  @click="removeBom(scope.$index)"
                  icon="Delete"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="描述">
        <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="输入描述"
        />
      </el-form-item>
    </el-form>

    <div class="form-actions">
      <el-button @click="cancel">取消</el-button>
      <el-button
          type="primary"
          @click="submitForm"
          v-if="mode !== 'view'"
      >
        保存
      </el-button>
    </div>

    <!-- BOM选择弹框 -->
    <bom-dialog
        ref="bomDialogRef"
        @handleBomSelectionChange="handleBomSelectionChange"
        @confirmBomSelect="confirmBomSelect"
    />
  </div>
</template>

<style scoped lang="scss">
.product-form {
  padding: 20px;
  background: #fff;
  height: 100%;
  overflow-y: auto;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;

    h3 {
      margin: 0;
      font-size: 18px;
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    margin-top: 30px;
  }

  :deep(.el-input.is-disabled .el-input__wrapper) {
    background-color: var(--el-input-disabled-bg-color, var(--el-disabled-bg-color));
  }

  :deep(.el-input.is-disabled .el-input__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }

  :deep(.el-textarea.is-disabled .el-textarea__inner) {
    color: var(--el-text-color-primary);
    -webkit-text-fill-color: var(--el-text-color-primary);
  }
}
</style>
